

import Layout from '@/views/layout/layout'
import { constantRouterMap } from '../../router/router'
import router from '../../router/router'
const _import = require('../../router/_import_' + process.env.NODE_ENV)

/**
 * routes.role判断是否与当前用户权限匹配
 * @param roles   //用户权限
 * @param routes   //路由表
 */
function hasPermission (routes, roles) {
    if (routes.role && routes.role.length > 0 && routes.status == 1) {
        return routes.role.includes(roles);
    } else {
        return false
    }
}

/**
 *
 * @param component   // 动态添加component
 */
function hasComponent (component) {
    if (component === 'Layout') {
        return Layout;
    } else {
        return _import(component)
    }
}

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles   //用户权限
 * @param routes   //后端返的路由表
 */

function filterAsyncRouter (routes, roles) {  //递归循环获取有权限的路由表
    const res = []
    routes.forEach((route) => {
        if (hasPermission(route, roles)) { //判断路由表是否与当前用户权限匹配,匹配返回前端所需要的路由表
            let tmp = Object.assign({}, { path: `${route.action}`, meta: { roles: route.role, title: route.name, sonRoles: route.children }, component: hasComponent(route.component) })
            if (route.children) {
                tmp.children = filterAsyncRouter(route.children, roles)
            }
            res.push(tmp)
        }
    })
    return res
}

const permission = {
    state: {
        addRouters: [],  //有权限的路由表
        Routers: []
    },
    mutations: {
        SET_ADDROUTERS: (state, routers) => {
            state.addRouters = [...constantRouterMap, ...routers]
        },
        SET_ROUTERS (state, routers) {
            state.Routers = routers
        },
        REM_ADDROUTERS (state) {
            state.addRouters = []
        }
    },
    actions: {
        GenerateRoutes ({ commit }, roles) {  //生成动态路由表
            return new Promise((resolve) => {
                this._vm.api.getAuth().then(res => { //获取动态路由表
                    const addRouters = filterAsyncRouter(res.data, roles)  //根据后端返给的路由表进行权限匹配,有权限则把有权限的返回
                    commit('SET_ADDROUTERS', addRouters)
                    commit('SET_ROUTERS', res.data)
                    console.log(addRouters)
                    router.addRoutes(addRouters)  //动态挂载有权限的路由表
                    resolve(addRouters)
                })
            })
        }
    }
}

export { permission }
